<?php


namespace app\common\business;


use think\Exception;

class SpecsValue extends BusBase
{
    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\SpecsValue();
    }

    public function getBySpecsId($specs_id)
    {
        try {
            $res = $this->model->getNormalBySpecsId($specs_id);
        } catch (Exception $e) {
            return [];
        }

        return $res->toArray();
    }

    public function dealGoodsSkus($gids, $flag_value)
    {
        $specs_data = array_keys($gids);

        $specs_value_ids = [];
        foreach ($specs_data as $v) {
            $tmp = explode(',', $v);
            foreach ($tmp as $k => $item) {
                $new[$k][] = $item;
                $specs_value_ids [] = $item;
            }
        }

        $specs_value_ids = array_unique($specs_value_ids);
        //获得规格
        $specs_values = $this->getNormalInIds($specs_value_ids);

        $data = [];
        $flag_value = explode(',', $flag_value);

        foreach ($new as $key => $item) {
            $new_value = array_unique($item);
            $list = [];
            foreach ($new_value as $v) {
                $list[] = [
                    'id' => $v,
                    'name' => $specs_values[$v]['name'],
                    'flag' => in_array($v, $flag_value),
                ];
            }

            $data[$key] = [
                'name' => $specs_values[$new_value[0]],
                'list' => $list,
            ];
        }

        return $data;

    }

    public function getNormalInIds(array $specs_value_ids)
    {
        try {
            $res = $this->model->getNormalInIds($specs_value_ids);
        } catch (Exception $e) {
            return [];
        }

        $specs_names = config('specs');
        $specs_names_arrs = array_column($specs_names, 'name', 'id');

        $data = [];
        foreach ($res as $item) {
            $data[$item['id']] = [
                'name' => $item['name'],
                'specs_name' => $specs_names_arrs[$item['specs_id']],
            ];
        }

        return $data;
    }


    public function dealSpecsValue($sku_specs_value_ids)
    {
        $ids = array_values($sku_specs_value_ids);
        $ids = implode(',', $ids);
        $ids = array_unique(explode(',', $ids));
        $res = $this->getNormalInIds($ids);

        if (!$res) {
            return [];
        }

        $data = [];
        foreach ($sku_specs_value_ids as $sku_id => $item) {
            $specs = explode(',', $item);
            $sku_str = [];
            foreach ($specs as $spec) {
                $sku_str[] = $res[$spec]['specs_name'] . ':' . $res[$spec]['name'];
            }
            $data[$sku_id] = implode(' ', $sku_str);
        }
        return $data;
    }
}